1
|
|
|
/* |
2
|
|
|
* to-bytes: bytes to numbers and strings. |
3
|
|
|
* Copyright (c) 2017 Rafael da Silva Rocha. |
4
|
|
|
* https://github.com/rochars/byte-data |
5
|
|
|
*/ |
6
|
|
|
|
7
|
|
|
const helpers = require("../src/helpers.js"); |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Turn numbers and strings to bytes. |
11
|
|
|
* @param {!Array<number>|number|string} values The data. |
12
|
|
|
* @param {Object} type One of the available types. |
13
|
|
|
* @return {!Array<number>|!Array<string>|Uint8Array} the data as a byte buffer. |
14
|
|
|
*/ |
15
|
|
|
function toBytes(values, type) { |
16
|
|
|
let bytes = writeBytes(values, type); |
17
|
|
|
helpers.makeBigEndian(bytes, type); |
18
|
|
|
helpers.outputToBase(bytes, type.bits, type.base); |
19
|
|
|
helpers.fixFloat16Endianness(bytes, type); |
20
|
|
|
return bytes; |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Write values as bytes. |
25
|
|
|
* @param {!Array<number>|number|string} values The data. |
26
|
|
|
* @param {Object} type One of the available types. |
27
|
|
|
* @return {!Array<number>} the bytes. |
28
|
|
|
*/ |
29
|
|
|
function writeBytes(values, type) { |
30
|
|
|
let i = 0; |
31
|
|
|
let j = 0; |
32
|
|
|
let len = values.length; |
33
|
|
|
let bytes = []; |
34
|
|
|
while (i < len) { |
35
|
|
|
j = type.writer(bytes, checkOverflow(values[i], type), j); |
36
|
|
|
i++; |
37
|
|
|
} |
38
|
|
|
return bytes; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Limit the value according to the bit depth in case of |
43
|
|
|
* overflow or underflow. |
44
|
|
|
* @param {!Array<number>|number|string} value The data. |
45
|
|
|
* @param {Object} type The maximum value. |
46
|
|
|
*/ |
47
|
|
|
function checkOverflow(value, type) { |
48
|
|
|
if (!type.float) { |
49
|
|
|
if (value > type.max) { |
50
|
|
|
value = type.max; |
51
|
|
|
} else if(value < type.min) { |
52
|
|
|
value = type.min; |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
return value; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
module.exports.toBytes = toBytes; |
59
|
|
|
|